
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.sales.RepOffice;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.forms.AddNewRepOfficeForm;
import com.scalar.chiptrack.users.User;


public class AddNewRepOfficeAction extends ChipTrackAction {

    private static final String ACTION_NAME = "/addNewRepOffice.do" ;  // Added by Basha (08/08/2003)

    private ArrayList allrepoffices = new ArrayList();
    private String repoffice = null;

    public ActionForward execute (ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                                     throws Exception {

        HttpSession session = request.getSession();
        AddNewRepOfficeForm addNewRepOfficeForm = ( AddNewRepOfficeForm )form;


             User user = (User)session.getAttribute (SessionKeys.USER_KEY);

             if (user == null)
             {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
                return (mapping.findForward ("login"));
             }


		HashMap errors = new HashMap();
		request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

		HashMap info = new HashMap();
		request.setAttribute (SessionKeys.INFO_MESSAGES, info);


		AddNewRepOfficeForm addrepofficeform=(AddNewRepOfficeForm) form;
		String action = request.getParameter("action");
		int customerId = Integer.parseInt(request.getParameter("customerId"));
 		//System.out.println("action in rep office "+action +"customerId "+customerId);

		// Modified by Sarada on 3rd Feb 2004 to get all repoffices of that customer id
		request.setAttribute("repOffices",CustomerDAO.getAllRepOfficesWithActions(customerId));

	if ("disable".equalsIgnoreCase(request.getParameter("repofficestatus")) == true)
        {
          String repofficeToDelete = request.getParameter("repoffice");
          //System.out.println("repofficeToDelete  "+repofficeToDelete);

          if ((repofficeToDelete != null) && (repofficeToDelete.trim().length() != 0))
          {
           try {
		   // Modified by Sarada on 3rd Feb 2004 to disable repoffices of that customer id
                  CustomerDAO.deleteRepOffice( repofficeToDelete , customerId );
                  info.put (repofficeToDelete + " has been disabled", null);
               }
              catch (ScalarException se)
              {
                  se.printStackTrace ();
                  errors.put ("Internal Server Error", "Could not delete \"" + repofficeToDelete + "\"");
              }
          }
        }

        else if ("activate".equalsIgnoreCase(request.getParameter("repofficestatus")) == true)
        {
            String repofficeToActivate = request.getParameter("repoffice");
           // System.out.println("repofficeToActivate  "+repofficeToActivate);
          if ((repofficeToActivate != null) && (repofficeToActivate.trim().length() != 0))
          {
            try
            {
		    // Modified by Sarada on 3rd Feb 2004 to enable repoffices of that customer id
              CustomerDAO.activateRepOffice ( repofficeToActivate , customerId );
              info.put (repofficeToActivate + " has been activated", null);
            }
            catch (ScalarException se)
            {
              se.printStackTrace ();
              errors.put ("Internal Server Error", "Could not activate \"" + repofficeToActivate + "\"");
            }
          }
        }

		if("insertRepOffice".equalsIgnoreCase(action))
		{
			//region = addregionform.getNewRegion();
			//repoffice = request.getParameter("newRepOffice");
            repoffice = addNewRepOfficeForm.getNewRepOffice();
			boolean success = false;
			boolean temp = false;


			if((repoffice == null) || (repoffice.trim().length() == 0)) {
				errors.put ( ERROR_CUSTOMER_INVALID_REP_OFFICE, null );
				return (mapping.findForward ("success"));
			}


			allrepoffices = CustomerDAO.getAllRepOfficesWithActions(customerId);
			int allrepofficeSize = allrepoffices.size();
			RepOffice repOffice = new  RepOffice();
			for (int j=0; j<allrepofficeSize; j++)
			{
				repOffice =  (RepOffice)allrepoffices.get(j);
				String  repofficename =  repOffice.getRepOffice();
				//System.out.println("repoffice"+repoffice+"   end");

				if( (repoffice != null) && (repofficename != null) )
				{
					if (repoffice.trim().equalsIgnoreCase(repofficename))
					{
						temp= true;
						break;
					}
				}
			}//for end

			if (temp == true) {
				errors.put ( repoffice +" " + ERROR_CUSTOMER_REP_ALREADY_EXISTS, null );
				return (mapping.findForward ("success"));
			}

			try {
				// Modified by Sarada on 3rd Feb 2004 to insert repoffices of that customer id
				CustomerDAO.insertRepOffice (null, repoffice, customerId);
                addNewRepOfficeForm.setNewRepOffice("");
				info.put ( INFO_REGIONAL_REP_SUCCESSFULLY_STORED, null );
				success = true;
			}
			catch (ScalarException se) {
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				//errors.put ("Internal Server Error", "Could not cancel packingslip (" + packingSlipForm.getLabel() + ")");
				se.printStackTrace();
			}
        }
        request.setAttribute("repOffices",CustomerDAO.getAllRepOfficesWithActions(customerId));
        return (mapping.findForward ("success"));
    }

}
